<template>
  <div class="health-diet pad">
    <div class="head">
      <span>健康食谱食物管理</span>
      <el-button @click="openAddDialog" icon="el-icon-plus" circle type="primary"></el-button>
    </div>
    <div class="search m-t-b" v-if="false">
      <el-input v-model="searchTxt" placeholder="食谱名称" clearable @input="clearSearch" />
      <el-button type="primary" @click="handleSearch" >
        <i class="el-icon-search"></i> 搜索
      </el-button>
    </div>
    <el-table class="m-t-b" border stripe :data="foods" v-loading="loading">
      <el-table-column label="食物名称" prop="foodName"></el-table-column>
      <el-table-column label="所属餐类">
        <template slot-scope="scope">
          {{categories[scope.row.type1 - 1]}}
        </template>
      </el-table-column>
      <el-table-column label="所属类别" prop="type2"></el-table-column>
      <!-- <el-table-column label="关联消息编号" prop="remindNum"></el-table-column> -->
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="updateDiet(scope.row)" type="default" icon="el-icon-edit" circle></el-button>
          <el-button disabled @click="deleteFood(scope.row)" type="danger" icon="el-icon-delete" circle></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="m-t-b flex"
      :page-size="pageSize"
      layout="prev, pager, next"
      :current-page="curPage"
      @current-change="handlePageChange"
      :total="total">
    </el-pagination>
    <el-dialog :title="dialogTitle" :visible.sync="showDialog">
      <el-form :model="food" label-position="top" :rules="rules" ref="diet">
        <el-form-item label="食物名称" prop="foodName">
          <el-input v-model="food.foodName" clearable />
        </el-form-item>
        <el-form-item v-if="!isUpdate" label="所属餐类" prop="type1">
          <el-select @change="changeType" v-model="food.type1" placeholder="请选择所属餐类">
            <el-option label="早餐" :value="1"></el-option>
            <el-option label="午餐" :value="2"></el-option>
            <el-option label="晚餐" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item  v-if="!isUpdate" label="所属类别" prop="type2">
          <el-select v-model="food.type2">
            <el-option v-for="(item, i) in types" :key="i" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideDialog">取 消</el-button>
        <el-button type="primary" @click="handleConfirm('diet')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { notifySuccess, fileToBase64 } from '../util'
import {
  addDietFood,
  updateDietFood,
  deleteDietFood,
  getDietFoodList
} from '../api'

export default {
  name: 'health-diet',
  data () {
    return {
      editorConfig: {},
      dialogTitle: '添加食物',
      pageSize: 10,
      loading: true,
      isUpdate: true,
      curPage: 1,
      total: 0,
      showDialog: false,
      searchTxt: '',
      foods: [],
      categories: ['早餐', '午餐', '晚餐'],
      types: [1, 2],
      food: {
        type1: '',
        type2: '',
        foodName: ''
      },
      rules: {
        foodName: [
          { required: true, message: '该项不能为空', trigger: 'blur' },
          { min: 2, max: 15, message: '食物名称必须为2 - 15个字符', trigger: 'blur' }
        ],
        type1: [
          { required: true, message: '该项不能为空', trigger: 'change' }
        ],
        type2: [
          { required: true, message: '该项不能为空', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    deleteFood (food) { // 删除食物
      console.log(food)
    },
    changeType () {
      if (this.food.type1 === 1) {
        this.types = [1, 2];
        if (this.food.type2 >= 3) {
          this.food.type2 = 2
        }
      } else {
        this.types = [1, 2, 3, 4, 5]
      }
    },
    handleSearch () {
      if (!this.searchTxt.trim()) {
        this.searchTxt = ''
        return this.$message.error('请输入搜索内容!')
      }
      this.fetchFoodList(1, this.searchTxt)
    },
    clearSearch () {
      if (!this.searchTxt) {
        this.fetchRecipeList(1)
      }
    },
    handlePageChange (page) {
      this.fetchFoodList(page)
    },
    updateDiet (data) {
      if (!this.$checkAuth('canEditFood')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.isUpdate = true
      this.dialogTitle = '修改食物'
      this.food.foodName = data.foodName;
      this.food.type1 = data.type1;
      this.food.type2 = data.type2;
      this.food.foodId = data.foodId;
      console.log(data)
      this.showDialog = true
    },
    handleAvatarSuccess (res, file) {
      this.diet.recipesPic = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isType = isJPG || isPNG
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isType) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isType && isLt2M
    },
    openAddDialog () {
      if (!this.$checkAuth('canAddFood')) {
        return this.$message.error('暂无对应操作权限!')
      };
      this.isUpdate = false;
      this.food.foodName = '';
      this.food.type1 = '';
      this.food.type2 = '';
      this.dialogTitle = '添加食物'
      this.showDialog = true
    },
    hideDialog () {
      this.showDialog = false
    },
    handleConfirm (form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          if (this.dialogTitle === '修改食物') {
            updateDietFood({
              foodId: this.food.foodId,
              type1: null,
              type2: null,
              foodName: this.food.foodName
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                });
                this.showDialog = false
                this.fetchFoodList(1)
              } else {
                this.$message.error(res.data.msg || '网络异常!')
              }
            })
            .catch(e => {
              this.$message.error('网络异常!')
            })
          } else {
            addDietFood({
              type1: this.food.type1,
              type2: this.food.type2,
              foodName: this.food.foodName
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                });
                this.showDialog = false
                this.fetchFoodList(1)
              } else {
                this.$message.error(res.data.msg || '网络异常!')
              }
            })
            .catch(e => {
              this.$message.error('网络异常!')
            })
          }
        } else {
          return false
        }
      })
    },
    fetchFoodList (index, foodName) {
      this.loading = true;
      foodName = foodName || null;
      getDietFoodList({
        index: index,
        count: this.pageSize,
        queryParam: {
          type1: null, //  //三餐类型(1早餐2午餐3晚餐)  (Integer)
          type2: null, //  //食物类型(早12,午12345,晚12345)  (Integer)
          foodName: foodName, //  //食物名字(String)
        }
      })
      .then(res => {
        if (res.data.code === 1) {
          this.total = res.data.data.totalRecord;
          this.foods = res.data.data.list || [];
        } else {
          this.$message.error(res.data.msg || '网络异常!')
        };
        this.loading = false
      })
      .catch(e => {
        this.loading = false;
        this.$message.error('网络异常!')
      })
    }
  },
  created () {
    // this.fetchRecipeList(1)
    // this.fetchServiceMsg()
    this.fetchFoodList(1)
  }
}
</script>
<style lang="scss">
  .health-diet {
    .search {
      display: flex;
    }
    table {
      .cell {
        text-align: center;
      }
    }
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      width: 358px;
      height: 178px;
      .tip-wrap {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
      }
    }
    .avatar-uploader .el-upload:hover {
      border-color: $main-color;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
    }
    .avatar {
      width: 358px;
      height: 178px;
      display: block;
    }
  }
</style>
